#!/usr/bin/env node

/**
 * 示例 MCP 服务器
 * 用于测试 MCP Tool Debugger
 */

const readline = require('readline');

// 定义可用的工具
const tools = [
  {
    name: 'echo',
    description: '回显输入的消息',
    inputSchema: {
      type: 'object',
      properties: {
        message: {
          type: 'string',
          description: '要回显的消息',
        },
      },
      required: ['message'],
    },
  },
  {
    name: 'add',
    description: '两个数字相加',
    inputSchema: {
      type: 'object',
      properties: {
        a: {
          type: 'number',
          description: '第一个数字',
        },
        b: {
          type: 'number',
          description: '第二个数字',
        },
      },
      required: ['a', 'b'],
    },
  },
  {
    name: 'greet',
    description: '生成问候语',
    inputSchema: {
      type: 'object',
      properties: {
        name: {
          type: 'string',
          description: '要问候的名字',
        },
        formal: {
          type: 'boolean',
          description: '是否使用正式问候',
          default: false,
        },
      },
      required: ['name'],
    },
  },
  {
    name: 'get_info',
    description: '获取系统信息',
    inputSchema: {
      type: 'object',
      properties: {},
    },
  },
  {
    name: 'format_text',
    description: '使用各种选项格式化文本',
    inputSchema: {
      type: 'object',
      properties: {
        text: {
          type: 'string',
          description: '要格式化的文本',
        },
        style: {
          type: 'string',
          description: '格式化样式',
          enum: ['uppercase', 'lowercase', 'capitalize', 'reverse'],
          default: 'capitalize',
        },
      },
      required: ['text'],
    },
  },
];

// 工具实现
const toolImplementations = {
  echo: (args) => {
    return {
      content: [
        {
          type: 'text',
          text: `回显: ${args.message}`,
        },
      ],
    };
  },

  add: (args) => {
    const result = args.a + args.b;
    return {
      content: [
        {
          type: 'text',
          text: `${args.a} + ${args.b} = ${result}`,
        },
      ],
      result: result,
    };
  },

  greet: (args) => {
    const greeting = args.formal
      ? `您好，${args.name}。很高兴见到您。`
      : `嗨 ${args.name}！最近怎么样？`;
    return {
      content: [
        {
          type: 'text',
          text: greeting,
        },
      ],
    };
  },

  get_info: () => {
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(
            {
              platform: process.platform,
              nodeVersion: process.version,
              arch: process.arch,
              uptime: process.uptime(),
              memory: process.memoryUsage(),
            },
            null,
            2
          ),
        },
      ],
    };
  },

  format_text: (args) => {
    let formatted = args.text;
    switch (args.style || 'capitalize') {
      case 'uppercase':
        formatted = formatted.toUpperCase();
        break;
      case 'lowercase':
        formatted = formatted.toLowerCase();
        break;
      case 'capitalize':
        formatted = formatted.charAt(0).toUpperCase() + formatted.slice(1);
        break;
      case 'reverse':
        formatted = formatted.split('').reverse().join('');
        break;
    }
    return {
      content: [
        {
          type: 'text',
          text: formatted,
        },
      ],
    };
  },
};

// 处理请求
function handleRequest(request) {
  const { method, params, id } = request;

  try {
    switch (method) {
      case 'initialize':
        return {
          jsonrpc: '2.0',
          id,
          result: {
            protocolVersion: '2024-11-05',
            capabilities: {
              tools: {},
            },
            serverInfo: {
              name: 'example-mcp-server',
              version: '1.0.0',
            },
          },
        };

      case 'tools/list':
        return {
          jsonrpc: '2.0',
          id,
          result: {
            tools: tools,
          },
        };

      case 'tools/call':
        const { name, arguments: args } = params;
        if (!toolImplementations[name]) {
          throw new Error(`Tool '${name}' not found`);
        }
        const result = toolImplementations[name](args || {});
        return {
          jsonrpc: '2.0',
          id,
          result: result,
        };

      default:
        throw new Error(`Unknown method: ${method}`);
    }
  } catch (error) {
    return {
      jsonrpc: '2.0',
      id,
      error: {
        code: -32603,
        message: error.message,
      },
    };
  }
}

// 主程序
function main() {
  console.error('示例 MCP 服务器已启动');
  console.error('协议版本: 2024-11-05');
  console.error('可用工具数:', tools.length);
  console.error('---');

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false,
  });

  rl.on('line', (line) => {
    try {
      const request = JSON.parse(line);
      const response = handleRequest(request);
      console.log(JSON.stringify(response));
    } catch (error) {
      console.error('处理请求出错:', error);
      console.log(
        JSON.stringify({
          jsonrpc: '2.0',
          error: {
            code: -32700,
            message: 'Parse error',
          },
        })
      );
    }
  });

  rl.on('close', () => {
    console.error('MCP 服务器已停止');
    process.exit(0);
  });
}

// 启动服务器
main();
